package org.hq.util;

import jakarta.annotation.PostConstruct;
import lombok.Getter;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class OkHttps {
    Logger logger = LoggerFactory.getLogger(OkHttps.class);
    @Getter
    private OkHttpClient client;

    /**
     * 服务初始化
     */
    @PostConstruct
    private void init() {
        // 创建Dispatcher实例
        Dispatcher dispatcher = new Dispatcher();
        // 设置最大并发请求数
        dispatcher.setMaxRequests(64);
        // 设置每个主机的最大并发请求数
        dispatcher.setMaxRequestsPerHost(64);
        // 创建连接池实例
        ConnectionPool pool = new ConnectionPool(20, 5L, TimeUnit.MINUTES);
        // 创建连接池实例
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectionPool(pool);
        builder.dispatcher(dispatcher);
        builder.connectTimeout(30L, TimeUnit.SECONDS);
        builder.readTimeout(30L, TimeUnit.SECONDS);
        builder.writeTimeout(30L, TimeUnit.SECONDS);
        builder.retryOnConnectionFailure(true);
        this.client = builder.build();

    }
    /**
     * 模拟 qq 浏览器请求头
     *
     * @return 返回请求头
     */
    private final Map<String, String> responseHeader() {
        Map<String, String> headers = new HashMap<>();
        headers.put("Sec-Ch-Ua", "Not)A;Brand;v=24, Chromium;v=116");
        headers.put("Sec-Ch-Ua-Mobile", "?0");
        headers.put("Sec-Ch-Ua-Platform", "Windows");
        headers.put("Sec-Fetch-Dest", "document");
        headers.put("Sec-Fetch-Mode", "navigate");
        headers.put("Sec-Fetch-Site", "same-origin");
        headers.put("Sec-Fetch-User", "?1");
        headers.put("Upgrade-Insecure-Requests", "1");
        String useragent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.5845.97 Safari/537.36 Core/1.116.438.400 QQBrowser/13.0.6071.400";
        headers.put("user-agent", useragent);
        return headers;
    }

    /**
     * get 同步 请求
     *
     * @param path 请求路径
     * @return 成功返回数据 失败返回 null
     */
    public final String getRequestToStringSync(String path) throws IOException {
        String result = null;
        Request.Builder url = new Request.Builder().url(path);
        for (Map.Entry<String, String> entry : responseHeader().entrySet()) {
            url.addHeader(entry.getKey(), entry.getValue());
        }
        Request getRequest = url.get().build();
        //准备好请求的Call对象
        Call call = this.client.newCall(getRequest);

        Response response = call.execute();
        if (response.code() == 200) {
            result = response.body().string();
        }

        //释放资源
        if (response != null) {
            response.body().close();
        }
        if (call != null) {
            call.cancel();
        }
        return result;
    }
}
